#!/usr/bin/python
import socket
import struct
VERSION = 0x00020001
MODULE_LOGIN_REQ = 0x00006001
MODULE_LOGIN_RESP = 0x00006002
HEARTBEAT_LINK_REQ = 0x00006005
HEARTBEAT_LINK_RESP = 0x00006006

def command_id_handle(header,body):
    buf_header = None
    buf_body = None

    if header[1] == 0x00006001:
        header_resp = (0x00020001,0x00006002,0,header[3],0)
        print repr(body)
        try:
            body_stuct = struct.unpack("II16s",body)
            print body_stuct[0]
        except:
            print "unpack error in command_id_handle"
            print repr(body)

    if header[1] == 0x00006005:
        header_resp = (0x00020001,0x00006006,0,header[3],0)

    buf_header = struct.pack("IIIII",header_resp[0],header_resp[1],header_resp[2],header_resp[3],header_resp[4])
        

    return buf_header

if __name__ == '__main__':
    print "CDR moniter"
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(('0.0.0.0',9999))
    sock.listen(5)
    connection = None
    while True:
        try:
            print "wait connection" 
            connection,address = sock.accept()
            print "get a connection", address 
            connection.settimeout(6000)
            while True:
                buf = connection.recv(struct.calcsize('IIIII'))
                if buf == '':
                    break
                header = struct.unpack("IIIII",buf)
                print "header:\nversion\t\t[%x]\
                    \ncommmand_id\t[%x]\
                    \nlength\t\t[%d]\
                    \nsequence\t[%d]\
                    \nstatus\t\t[%d]\n"\
                    %(header[0],header[1],header[2],header[3],header[4])
                if header[0] != 0x00020001:
                    print "version error\t[%x]"%(header[0])
                    break

                body = None
                if header[2] != 0 :
                    body = connection.recv(header[2])
    
                #========================================
                buf = command_id_handle(header,body)
                connection.send(buf)
                buf = None


        except socket.timeout:
            print "socket.timeout"
            connection.send('time out')
            connection.close()
            sock.close()
            break

        except KeyboardInterrupt:
            if connection != None :
                connection.close()

            print "Ctrl+C exception"
            break

        except:
            connection.close()
            sock.close()
            print "other exception"
            break
        connection.close()
        print "connection closed"

    sock.close()
